package com.rabbiter.hospital.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbiter.hospital.mapper.PatientMapper;
import com.rabbiter.hospital.pojo.Patients;
import com.rabbiter.hospital.service.PatientService;
import com.rabbiter.hospital.utils.Md5Util;
import com.rabbiter.hospital.utils.TodayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

@Service("PatientService")
public class PatientServiceImpl extends ServiceImpl<PatientMapper,Patients> implements PatientService {
    protected static final Logger Log = LoggerFactory.getLogger(PatientServiceImpl.class);

    @Resource
    private PatientMapper patientMapper;


    /**
     * 登录数据校验
     */
    @Override
    public Patients login(int pId, String pPassword) {
        Patients patient = this.patientMapper.selectById(pId);
        if (patient == null || 0 == patient.getPState()) {
            return null;
        }
        String password = Md5Util.getMD5(pPassword);
        if ((patient.getPPassword()).equals(password)) {
            return patient;
        }
        return null;
    }

    /**
     * 分页模糊查询所有患者信息
     */
    @Override
    public HashMap<String, Object> findAllPatients(int pageNumber, int size, String query) {
        Page<Patients> page = new Page<>(pageNumber, size);
        QueryWrapper<Patients> wrapper = new QueryWrapper<>();
        wrapper.like("p_name", query).eq("p_state", 1);
        IPage<Patients> iPage = this.patientMapper.selectPage(page, wrapper);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("total", iPage.getTotal());       //总条数
        hashMap.put("pages", iPage.getPages());       //总页数
        hashMap.put("pageNumber", iPage.getCurrent());//当前页
        hashMap.put("patients", iPage.getRecords()); //查询到的记录
        return hashMap;
    }

    /**
     * 删除患者信息
     */
    @Override
    public Boolean deletePatient(int pId) {
        Patients patient = new Patients();
        patient.setPId(pId);
        patient.setPState(0);
        this.patientMapper.updateById(patient);
        return true;
    }

    /**
     * 根据患者id查询患者信息
     */
    @Override
    public Patients findPatientById(int pId) {
        QueryWrapper<Patients> wrapper = new QueryWrapper<>();
        wrapper.eq("p_id", pId);
        return this.patientMapper.selectOne(wrapper);
    }

    /**
     * 增加患者信息
     */
    @Override
    public Boolean addPatient(Patients patient) {
//        //如果账号已存在则返回false
//        List<Patients> patients = this.patientMapper.selectList(null);
//        for (Patients patient1 : patients) {
//            if (patient.getPId() == patient1.getPId()) {
//                return false;
//            }
//            if ((patient.getPEmail()).equals(patient1.getPEmail())) {
//                return false;
//            }
//        }
//        int yourYear = Integer.parseInt(patient.getPBirthday().substring(0, 4));
//        int todayYear = Integer.parseInt(TodayUtil.getTodayYmd().substring(0, 4));
//        //密码md5加密
//        String password = Md5Util.getMD5(patient.getPPassword());
//        patient.setPPassword(password);
//        patient.setPAge(todayYear - yourYear);
//        patient.setPState(1);
//        this.patientMapper.insert(patient);
//        return true;
        System.out.println("Adding patient: " + patient);
        // 检查患者信息是否有效
        if (patient.getPName() == null || patient.getPName().isEmpty()) {
            throw new IllegalArgumentException("患者姓名不能为空");
        }
        if (patient.getPGender() == null || patient.getPGender().isEmpty()) {
            throw new IllegalArgumentException("患者性别不能为空");
        }
        if (patient.getPAge() == null || patient.getPAge() <= 0) {
            throw new IllegalArgumentException("患者年龄必须大于0");
        }
        if (patient.getPCard() == null || patient.getPCard().isEmpty()) {
            throw new IllegalArgumentException("患者身份证号不能为空");
        }
        if (patient.getPPhone() == null || patient.getPPhone().isEmpty()) {
            throw new IllegalArgumentException("患者手机号不能为空");
        }
        if (patient.getPEmail() == null || patient.getPEmail().isEmpty()) {
            throw new IllegalArgumentException("患者邮箱不能为空");
        }

        // 校验身份证号
        if (!isValidIdCard(patient.getPCard())) {
            throw new IllegalArgumentException("患者身份证号格式不正确");
        }

        // 校验手机号
        if (!isValidPhoneNumber(patient.getPPhone())) {
            throw new IllegalArgumentException("患者手机号格式不正确");
        }

        // 校验邮箱
        if (!isValidEmail(patient.getPEmail())) {
            throw new IllegalArgumentException("患者邮箱格式不正确");
        }


        // 插入患者信息
        boolean result = patientMapper.insert(patient) > 0;
        System.out.println("Result of inserting patient: " + result);
        return result;
    }

        private boolean isValidIdCard (String idCard){
            // 中国身份证号长度为18位
            if (idCard.length() != 18) {
                return false;
            }
            // 简单的正则表达式校验
            String regex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
            return Pattern.matches (regex,idCard);
        }

        private boolean isValidPhoneNumber (String phoneNumber){
            // 中国大陆手机号码长度为11位
            if (phoneNumber.length() != 11) {
                return false;
            }
            // 简单的正则表达式校验
            String regex = "^1[3-9]\\d{9}$";
            return Pattern.matches(regex, phoneNumber);
        }

        private boolean isValidEmail (String email){
            // 常用的邮箱正则表达式
            String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
            return Pattern.matches(regex, email);
        }




    /**
     * 统计患者男女人数
     */
    public List<Integer> patientAge() {
        List<Integer> ageList = new ArrayList<>();
        Integer age1 = this.patientMapper.patientAge(0, 9);
        Integer age2 = this.patientMapper.patientAge(10, 19);
        Integer age3 = this.patientMapper.patientAge(20, 29);
        Integer age4 = this.patientMapper.patientAge(30, 39);
        Integer age5 = this.patientMapper.patientAge(40, 49);
        Integer age6 = this.patientMapper.patientAge(50, 59);
        Integer age7 = this.patientMapper.patientAge(60, 69);
        Integer age8 = this.patientMapper.patientAge(70, 79);
        Integer age9 = this.patientMapper.patientAge(80, 89);
        Integer age10 = this.patientMapper.patientAge(90, 99);
        ageList.add(age1);
        ageList.add(age2);
        ageList.add(age3);
        ageList.add(age4);
        ageList.add(age5);
        ageList.add(age6);
        ageList.add(age7);
        ageList.add(age8);
        ageList.add(age9);
        ageList.add(age10);
        return ageList;

    }


}


